package com.ruoyi.Factory.controller;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.Factory.domain.General;
import com.ruoyi.Factory.service.GeneralService;
import com.ruoyi.Factory.service.impl.GeneralServiceImpl;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/General/general")
public class GeneralController extends BaseController
{
    @Autowired
    private GeneralService generalService;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /*查询*/
    /* 分页列表 - 加 project 参数 */
    @GetMapping("/list")
    public TableDataInfo list(General general, @RequestParam String project)   // ① 表名
    {
        String table = "t_general_" + project;
        List<General> list = generalService.selectGeneralList(general, table);
        return getDataTable(list);
    }

    /*获取*/
    @GetMapping(value = "/get")
    public AjaxResult getInfo(@RequestParam Long id, @RequestParam String project)
    {
        String table = "t_general_" + project;
        return success(generalService.selectGeneralById(id,table));
    }

    /*新增*/
    @PostMapping
    public AjaxResult add(@RequestBody Map<String, Object> dto)
    {
        General general = JSON.parseObject(JSON.toJSONString(dto.get("data")), General.class);
        String project = (String) dto.get("project");   // 工厂名
        String table = "t_general_" + project;
        return toAjax(generalService.insertGeneral(general,table));
    }

    /*修改*/
    @PutMapping
    public AjaxResult edit(@RequestBody Map<String,Object> dto)
    {
        General general = JSON.parseObject(JSON.toJSONString(dto.get("data")), General.class);
        String table = "t_general_"+ dto.get("project");
        return toAjax(generalService.updateGeneral(general,table));
    }

    /*删除*/
    @DeleteMapping("/batch")
    public AjaxResult remove(@RequestBody Map<String, Object> dto)
    {
        List<Long> ids = (List<Long>) dto.get("ids");
        String project = (String)dto.get("project");
        String table = "t_general_" + project;
        return toAjax(generalService.deleteGeneralByIds(ids,table));
    }

    @PostMapping("/createTable")
    public AjaxResult createTable(@RequestBody Map<String,String> dto) {
        String project = dto.get("project");
        String table = "t_general_" + project;
        // 字段清单（与实体类一一对应）
        String sql = "CREATE TABLE IF NOT EXISTS " + table + " (\n" +
                "  id bigint NOT NULL AUTO_INCREMENT,\n" +
                "  models varchar(50) DEFAULT NULL,\n" +
                "  station varchar(50) DEFAULT NULL,\n" +
                "  sj_number varchar(50) DEFAULT NULL,\n" +
                "  solder_joint varchar(50) DEFAULT NULL,\n" +
                "  x double DEFAULT NULL,\n" +
                "  y double DEFAULT NULL,\n" +
                "  z double DEFAULT NULL,\n" +
                "  torch_number varchar(50) DEFAULT NULL,\n" +
                "  robot varchar(50) DEFAULT NULL,\n" +
                "  rated_pressure varchar(50) DEFAULT NULL,\n" +
                "  gauge_number bigint DEFAULT NULL,\n" +
                "  energy varchar(50) DEFAULT NULL,\n" +
                "  splash_rate varchar(50) DEFAULT NULL,\n" +
                "  electrode_form varchar(50) DEFAULT NULL,\n" +
                "  material1 varchar(50) DEFAULT NULL,\n" +
                "  material_thickness1 double DEFAULT NULL,\n" +
                "  gumming1 varchar(50) DEFAULT NULL,\n" +
                "  material2 varchar(50) DEFAULT NULL,\n" +
                "  material_thickness2 double DEFAULT NULL,\n" +
                "  gumming2 varchar(50) DEFAULT NULL,\n" +
                "  material3 varchar(50) DEFAULT NULL,\n" +
                "  material_thickness3 double DEFAULT NULL,\n" +
                "  gumming3 varchar(50) DEFAULT NULL,\n" +
                "  material4 varchar(50) DEFAULT NULL,\n" +
                "  material_thickness4 double DEFAULT NULL,\n" +
                "  stress varchar(50) DEFAULT NULL,\n" +
                "  preloading_time double DEFAULT NULL,\n" +
                "  pressurization_time double DEFAULT NULL,\n" +
                "  preheating_time double DEFAULT NULL,\n" +
                "  preheating_current double DEFAULT NULL,\n" +
                "  cooling_time double DEFAULT NULL,\n" +
                "  incremental_time double DEFAULT NULL,\n" +
                "  starting_current double DEFAULT NULL,\n" +
                "  welding_time double DEFAULT NULL,\n" +
                "  welding_current double DEFAULT NULL,\n" +
                "  cooling_time1 double DEFAULT NULL,\n" +
                "  decline_time double DEFAULT NULL,\n" +
                "  termination_current double DEFAULT NULL,\n" +
                "  pulse_frequency double DEFAULT NULL,\n" +
                "  cooling_time2 double DEFAULT NULL,\n" +
                "  tempering_time double DEFAULT NULL,\n" +
                "  tempering_current double DEFAULT NULL,\n" +
                "  hold_time double DEFAULT NULL,\n" +
                "  parametric_form varchar(50) DEFAULT NULL,\n" +
                "  new_version double DEFAULT NULL,\n" +
                "  tempering_method varchar(50) DEFAULT NULL,\n" +
                "  preheating_method varchar(50) DEFAULT NULL,\n" +
                "  welding_method varchar(50) DEFAULT NULL,\n" +
                "  increase_decrease varchar(50) DEFAULT NULL,\n" +
                "  PRIMARY KEY (id)\n" +
                ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
        try {
            jdbcTemplate.execute(sql);
            return success("数据表 " + table + " 创建成功");
        } catch (DataAccessException e) {
            // ① 抛业务异常给前端
            String msg = "建表失败：" + Objects.requireNonNull(e.getRootCause()).getMessage();
            return error(msg);
        }
    }

    @PostMapping("/delTable")
    public AjaxResult delTable(@RequestBody Map<String,String> dto) {
        String project = dto.get("project");
        String table = "t_general_" + project;
        String sql = "DROP TABLE IF EXISTS `" + table + "`";
        try {
            jdbcTemplate.execute(sql);
            return success("数据表 " + table + " 删除成功");
        } catch (DataAccessException e) {
            // ① 抛业务异常给前端
            String msg = "删表失败：" + Objects.requireNonNull(e.getRootCause()).getMessage();
            return error(msg);
        }
    }

    /*清空数据库*/
    @DeleteMapping("/clear")
    public AjaxResult clearAllGeneral(String project)
    {
        String table = "t_general_" + project;
        return toAjax(generalService.ClearGeneral(table));
    }

    /*导出焊接/机器人*/
    @PostMapping("/export1")
    public void export1(Long[] ids,HttpServletResponse response,String project)
    {
        String table = "t_general_" + project;
        List<General> list = generalService.selectGeneralByIds(ids,table);
        generalService.exportByTemplate1(list,response);
    }

    /*根据id来导出模版表*/
    @PostMapping("/export3")
    public void exportTemplate(Long[] ids,HttpServletResponse response,String project)
    {
        String table = "t_general_" + project;
        List<General> list = generalService.selectGeneralByIds(ids,table);
        ExcelUtil<General> util = new ExcelUtil<>(General.class);
        util.exportExcel(response, list, "数据");
    }
    /*导出全部模版表*/
    @PostMapping("/exportAll")
    public void exportTemplateAll(General general, HttpServletResponse response,String project)
    {
        String table = "t_general_" + project;
        List<General> list = generalService.selectGeneralList(general,table);
        ExcelUtil<General> util = new ExcelUtil<>(General.class);
        util.exportExcel(response, list, "数据");
    }
    /*导出工艺验证表*/
    @PostMapping("/exportAll2")
    public void exportAll(General general, HttpServletResponse response,String project)
    {
        String table = "t_general_" + project;
        List<General> list = generalService.selectGeneralList(general,table);
        generalService.exportByTemplate2(list,response);
    }

    /*导入模版*/
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<General> util = new ExcelUtil<>(General.class);
        util.importTemplateExcel(response, "数据");
    }

    /*导入*/
    @PostMapping("/importData")
    public AjaxResult importGeneral(MultipartFile file, String project, Double version) throws Exception
    {
        String table = "t_general_" + project;
        ExcelUtil<General> util = new ExcelUtil<>(General.class);
        List<General> generalList = util.importExcel(file.getInputStream());
        generalList.forEach(g -> g.setNewVersion(version));

        String message = generalService.importGeneral(generalList, table);
        return success(message);
    }

    @PostMapping("/comparison")
    public R<Map<String,List<General>>> versionComparison(@RequestBody Map<String,String> dto, Double Version1, Double Version2)throws Exception
    {
        String project = dto.get("project");
        String table = "t_general_" + project;
        General general = new General();
        general.setNewVersion(Version1);
        List<General> generalList1 = generalService.selectGeneralList(general,table);
        general.setNewVersion(Version2);
        List<General> generalList2 = generalService.selectGeneralList(general,table);
        return R.ok(GeneralServiceImpl.versionComparison(generalList1,generalList2),"对比完成");
    }

}